﻿#include "card_operations.h"
Card* createCards(int n) {
	try {
		Card* p = new Card[n];
		return p;
	}
	catch (const std::bad_alloc& e) {
		std::cerr << "错误：内存分配失败！" << e.what() << std::endl;
		exit(EXIT_FAILURE);
	}
}

void destroyCards(Card* p) {
	delete[] p; 
	p = nullptr; 
}

void inputCards(Card* arr, int n) {
	for (int i = 0; i < n; ++i) {
		try {
			std::cout << "请输入第" << (i + 1) << "个学生的【学号 姓名 初始余额】：";
			std::cin >> arr[i].id >> arr[i].name >> arr[i].balance;
			if (std::cin.fail()) {
				std::cin.clear();
				std::cin.ignore(1000, '\n');
				throw std::runtime_error("输入格式错误！学号和余额必须是数字，姓名不能有空格。");
			}
			if (arr[i].balance < 0) {
				throw std::invalid_argument("初始余额不能为负数！请重新输入。");
			}
			arr[i].transactions = 0;
		}
		catch (const std::exception& e) {
			std::cout << " " << e.what() << std::endl;
			i--;
		}
	}
}
void deposit(Card& c, double amount, double fee) {
	try {
		if (amount < 0) {
			throw std::invalid_argument("充值金额不能为负数！");
		}
		double actualAmount = amount * (1.0 - fee);
		c.balance += actualAmount;
		c.transactions++; 
		std::cout << " 充值成功！实际到账：" << std::fixed << std::setprecision(2) << actualAmount << "元" << std::endl;
	}
	catch (const std::exception& e) {
		std::cout << " " << e.what() << std::endl;
	}
}

bool spend(Card& c, double cost) {
	try {
		if (cost < 0) {
			throw std::invalid_argument("消费金额不能为负数！");
		}
		if (c.balance < cost) {
			throw std::runtime_error("余额不足，消费失败！");
		}
		c.balance -= cost;
		c.transactions++;
		return true;
	}
	catch (const std::exception& e) {
		std::cout << " " << e.what() << std::endl;
		return false;
	}
}

bool spend(Card& c, double cost, const std::string& item) {
	std::cout << " 消费项目：" << item << "，金额：" << cost << "元" << std::endl;
	return spend(c, cost);
}

void showBalance(const Card& c) {
	std::cout << " " << c.name << " 的当前余额：" << std::fixed << std::setprecision(2) << c.balance << "元" << std::endl;
}

void viewStudentID(const Card* p) {
	std::cout << " 账户学号：" << p->id << std::endl;
}

int toCent(double amount) {
	return static_cast<int>(amount * 100);
}

void printReport(const Card* arr, int n) {
	std::cout << "\n======================= 校园一卡通账户报表 =======================" << std::endl;
	std::cout << std::left << std::setw(10) << "学号"
		<< std::setw(15) << "姓名"
		<< std::right << std::setw(15) << "当前余额（元）"
		<< std::setw(15) << "交易次数" << std::endl;
	std::cout << "---------------------------------------------------------------" << std::endl;

	std::cout << std::fixed << std::setprecision(2);
	for (int i = 0; i < n; ++i) {
		std::cout << std::left << std::setw(10) << arr[i].id
			<< std::setw(15) << arr[i].name
			<< std::right << std::setw(15) << arr[i].balance
			<< std::setw(15) << arr[i].transactions << std::endl;
	}
	std::cout << "===============================================================" << std::endl;
}